package com.pdd.commons.cdn;

import com.pdd.config.yml.ApiConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:liyangpeng
 * @date:2019/6/3 17:17
 */
@Component
public class TCCloudFactory {

    @Autowired
    private ApiConfig apiConfig;

    private COSClient cosClient;

    private ReentrantLock reentrantLock=new ReentrantLock();
    /**
     * 获取文件上传静态工厂的方法
     * @return
     */
    public COSClient getInstance(){
        if(cosClient==null){
            //此处使用重入锁防止多线程访问生成的对象不是同一个
            reentrantLock.lock();
            try {
                //双重检测
                if(cosClient==null){
                    COSCredentials cosCredentials=new BasicCOSCredentials(apiConfig.cdnAccessKey,apiConfig.cdnSecretKey);
                    ClientConfig clientConfig=new ClientConfig(new Region("ap-shanghai"));
                    cosClient=new COSClient(cosCredentials,clientConfig);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //解锁
                reentrantLock.unlock();
            }
        }
        return cosClient;
    }
}
